{% extends "helpdesk/public_base.html" %}{% load i18n %}

{% block helpdesk_body %}
<h2>{% trans "My Tickets" %}</h2>

<div class="container mt-4">
    <div class="form-check mb-2">
        <input class="form-check-input" type="checkbox" id="hideClosed" checked>
        <label class="form-check-label" for="hideClosed">
            {% trans "Hide Closed Tickets" %}
        </label>
    </div>

    <table class="table table-striped" id="ticketsTable">
        <thead>
            <tr>
                <th>{% trans "Title" %}</th>
                <th>{% trans "Queue" %}</th>
                <th>{% trans "Status" %}</th>
                <th>{% trans "Created" %}</th>
            </tr>
        </thead>
        <tbody>
            <!-- Rows will be added here dynamically using jQuery -->
        </tbody>
    </table>
    <nav aria-label="{% trans 'Page navigation' %}">
        <ul class="pagination" id="pagination">
            <!-- Pagination buttons will be added here dynamically -->
        </ul>
    </nav>
</div>

<script>
window.addEventListener('load', function() {
    const table = $('#ticketsTable').DataTable({
        paging: true,
        searching: true,
        ordering: true,
        columns: [
            { data: 'title',
              render: function(data, type, row) {
                  const safeTitle = $('<div>').html(data).html();
                  return `<a href='{% url "helpdesk:public_view" %}?ticket=${row.id}&email=${row.submitter}&key=${row.secret_key}'>${safeTitle}</a>`;
              }
            },
            { data: 'queue.title' },
            { data: 'status' },
            { data: 'created' }
        ]
    });

    let allTickets = [];

    function fetchTickets(page = 1) {
        const endpoint = '{% url "helpdesk:user_tickets-list" %}?page=' + page;

        $.get(endpoint, function(data) {
            allTickets = data.results.slice();
            renderTickets();
        });
    }

    function renderTickets() {
        let tickets = allTickets.slice();

        if ($('#hideClosed').is(':checked')) {
            const hiddenStatuses = ['closed', 'duplicate'];
            tickets = tickets.filter(ticket => !hiddenStatuses.includes(ticket.status.toLowerCase()));
        }

        table.clear().rows.add(tickets).draw();
    }

    // Re-fetch when checkbox changes
    $('#hideClosed').change(renderTickets);

    fetchTickets();
});
</script>

{% endblock %}
